﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

/* ############################################################################################
 *           Matthijs Hilgers - Gerben Boot - Marcel Boelen - Joep van den Hoven
 *               1580499          1575754        1582702            1592146         
 * ############################################################################################
 * 
 *  Date     || Changed                                  || By               || Source
 *  ===========================================================================================
 *  05-03-12 || First version                            || Gerben           || new
 */

namespace MultipleOutputNeuralNetwork {
    class ImageData {
        public int imageWidth;
        public int imageHeight;
        public int pixelFormat;
        public int imagePixels;

        /// <summary>
        /// locks the images in the memory and returns the bitmap data, 
        /// saves the imageWidth,imageHeight,the pixelFormat and the totalPixels.
        /// </summary>
        /// <param name="sourceImage">Bitmap</param>
        /// <returns>return an byte array with all rgb data of each bitmap pixel</returns>
        public byte[] bitmapToArray(Bitmap sourceImage) {
            Bitmap bmp = new Bitmap(sourceImage);
            //get memory data and fill rgbValues array with bitmap data from the memory
            Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
            BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadOnly, bmp.PixelFormat);
            imageWidth = bmpData.Width;
            imageHeight = bmpData.Height;
            int bytes = Math.Abs(bmpData.Stride) * bmp.Height;
            byte[] rgbValues = new byte[bytes];
            pixelFormat = (int)bmpData.Stride / bmpData.Width;
            Marshal.Copy(bmpData.Scan0, rgbValues, 0, rgbValues.Length);
            bmp.UnlockBits(bmpData);
            this.imagePixels = imageHeight * imageWidth;
            return rgbValues;
        }

        /// <summary>
        /// convert a byte array with rgbValues to a bitmap
        /// </summary>
        /// <param name="bmp">Destination Bitmap</param>
        /// <param name="rgbValues">array with rgb Values</param>
        /// <returns>new Bitmap</returns>
        public Bitmap arrayToBitmap(Bitmap bmp, byte[] rgbValues) {
            //return rgbValues to the bitmap using the lockImage method
            Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
            BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.WriteOnly, bmp.PixelFormat);
            Marshal.Copy(rgbValues, 0, bmpData.Scan0, rgbValues.Length);
            bmp.UnlockBits(bmpData);
            return bmp;
        }
    }
}